package com.example.boot0701.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile pic) throws IOException {
        System.out.println("pic = " + pic);
        //得到文件名
        String fileName = pic.getOriginalFilename();
        System.out.println("原始文件"+fileName);
        String sub = fileName.substring(fileName.lastIndexOf("."));
        //生成唯一文件名
       fileName = UUID.randomUUID()+sub;
        System.out.println("唯一文件名"+fileName);
       //准备保存上传文件的路径
        String dirPath = "E:/files";
        File dirFile = new File(dirPath);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //获得完整路径
        String filePath = dirPath+"/"+fileName;

        //保存图片
        pic.transferTo(new File(filePath));
        //把图片路径返回到前端的url
        return "/"+fileName;

    }
}
